<?php


namespace App\Libs\Contracts\Push\Huawei;


use App\Libs\httpUtil;
use App\Models\User;

class HuaweiPushService
{
    private $appSecret = "56ede05891a35be883b11fd310692d91";
    private $appId = "100592785";//用户在华为开发者联盟申请的appId和appSecret（会员中心->我的产品，点击产品对应的Push服务，点击“移动应用详情”获取）
    private $tokenUrl = "https://login.vmall.com/oauth2/token"; //获取认证Token的URL
    private $apiUrl = "https://api.push.hicloud.com/pushsend.do"; //应用级消息下发API
    private $accessToken;//下发通知消息的认证Token
    private $tokenExpiredTime;  //accessToken的过期时间
    private $void;//参数组

    public function push($title, $content, $userId)
    {

        $deviceTokenList = [];
        $payload = "";
        if ($userId) {
            $user = User::find($userId);
            if ($user['pushType'] == "HUAWEI") {
                if ($user['type'] == "ANDROID") {
                    $deviceTokenList[] = $user['registrationId'];
                }
            }
        } else {
            $user = User::select("registrationId")->where(['pushType' => "HUAWEI", 'type' => "ANDROID"])->get()->toArray();
            foreach ($user as $value) {
                $deviceTokenList[] = $value['registrationId'];
            }
        }
        $num = intval(floor(count($deviceTokenList) / 100));
        $sup = count($deviceTokenList) % 100;

        for ($i = 0; $i < $num; $i++) {
            $deviceToken = [];
            for ($j = 0; $j < 100; $j++) {
                if (@$deviceTokenList[$i * 100 + $j]) {
                    $deviceToken[] = $deviceTokenList[$i * 100 + $j];
                } else {
                    break;
                }
            }
            if ($deviceToken) {
                $this->send($title, $content, $deviceToken);
            }
        }
        $deviceToken = [];
        for ($i = 0; $i < $sup; $i++) {
            $deviceToken[] = $deviceTokenList[$num * 100 + $i];
        }
        if ($deviceToken) {
            $this->send($title, $content, $deviceToken);
        }
        return true;
    }


    private function send($title, $content, $deviceTokens)
    {
        \Log::info("华为推送");
        $intent = "kangtaicloud://com.xszb.kangtaicloud/messagelist?data=";
        $body = array();//仅通知栏消息需要设置标题和内容，透传消息key和value为用户自定义
        $body['title'] = $title;//消息标题
        $body['content'] = $content;//消息标题

        $param = array();
        $param['intent'] = $intent;//定义需要打开的appPkgName

        $action = array();

        $action['param'] = $param;//消息点击动作参数
        $action['type'] = 1;//类型3为打开APP，其他行为请参考接口文档设置

        $msg = array();

        $msg['action'] = $action;//消息点击动作
        $msg['type'] = 3;//3: 通知栏消息，异步透传消息请根据接口文档设置
        $msg['body'] = $body;//通知栏消息body内容

        $ext = array();//扩展信息，含BI消息统计，特定展示风格，消息折叠。
        $ext['biTag'] = 'Trump';//设置消息标签，如果带了这个标签，会在回执中推送给CP用于检测某种类型消息的到达率和状态
        $ext['icon'] = "";//自定义推送消息在通知栏的图标,value为一个公网可以访问的URL

        $hps = array();//华为PUSH消息总结构体
        $hps['msg'] = $msg;
        $hps['ext'] = $ext;

        $payload = array();
        $payload['hps'] = $hps;

        $postBody = 'access_token=' . urlencode($this->getAuthToken()) . '&nsp_svc=' . urlencode('openpush.message.api.send') . '&nsp_ts=' . (int)urlencode(msectime() / 1000)
            . '&device_token_list=' . urlencode(json_encode($deviceTokens)) . '&payload=' . urlencode(json_encode($payload));
        $postUrl = $this->apiUrl . '?nsp_ctx=' . urlencode("{\"ver\":\"1\", \"appId\":\"" . $this->appId . "\"}");
        $http = new httpUtil();
        $status = $response = $http->http_post($postUrl, $postBody);
        \Log::info($status);
    }

    private function refreshAuthToken()
    {

        $http = new httpUtil();
        $url = $this->tokenUrl;
        $param['grant_type'] = "client_credentials";
        $param['client_id'] = "100592785";
        $param['client_secret'] = "56ede05891a35be883b11fd310692d91";
        $result = $http->http_post($url, $param);

        if ($result) {
            $result = json_decode($result, true);
            $access_token = $result['access_token'];

            \RedisDB::setex(env("APP_NAME") . '-HUAWEI-authToken', 3600, $access_token);
            return $access_token;
        } else {
            \Log::error("获取HUAWEI authToken失败");
            \Log::error($result);
            return "";
        }


    }

    private function getAuthToken()
    {
        $authToken = \RedisDB::get(env("APP_NAME") . '-HUAWEI-authToken');

        if ($authToken) {
            return $authToken;
        } else {
            return $this->refreshAuthToken();
        }
    }


}